package com.example.lib_common.http

import com.example.lib_common.BuildConfig
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitManager {
    private val retrofit: Retrofit by lazy {
        Retrofit.Builder().baseUrl(getBaseUrl()).addConverterFactory(GsonConverterFactory.create())
            .client(getDefaultOkHttpClient()).build()
    }

    fun <T> create(
        service: Class<T>, baseUrl: String? = null, okHttpClient: OkHttpClient? = null
    ): T = if (baseUrl == null && okHttpClient == null) {
        retrofit.create(service)
    } else {
        val myUrl = baseUrl ?: getBaseUrl()
        val myOkHttpClient = okHttpClient ?: getDefaultOkHttpClient()
        val retrofit =
            Retrofit.Builder().baseUrl(myUrl).addConverterFactory(GsonConverterFactory.create())
                .client(myOkHttpClient).build()
        retrofit.create(service)
    }


    fun getBaseUrl(): String {
        return BuildConfig.BASE_URL
    }

    fun getDefaultOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder().addInterceptor(OkHttpInterceptor()).build()
    }
}